package com.bt.springboot.config;

import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zkx
 * @Date 2023/5/6 14:14
 */
@Configuration
public class SocketIOConfig {

	/**
	 * 服务器将监听的主机名或IP地址
	 */
	@Value("${socketio.host}")
	private String host;

	/**
	 * 指定服务器将运行的端口号
	 */
	@Value("${socketio.port}")
	private Integer port;

	/**
	 * 关于服务器进程的配置参数
	 */
	@Value("${socketio.bossCount}")
	private int bossCount;

	/**
	 * 关于服务器进程的配置参数
	 */
	@Value("${socketio.workCount}")
	private int workCount;

	/**
	 * 指定是否允许自定义请求类型。如果设置为“false”，则只有标准HTTP请求才能通过
	 */
	@Value("${socketio.allowCustomRequests}")
	private boolean allowCustomRequests;


	/**
	 * 指定升级握手过程的超时时间
	 */
	@Value("${socketio.upgradeTimeout}")
	private int upgradeTimeout;

	/**
	 * 指定在没有收到客户端的响应之前可以发送多长时间的ping请求。该值以毫秒为单位
	 */
	@Value("${socketio.pingTimeout}")
	private int pingTimeout;

	/**
	 * 指定在发送ping请求之间等待多长时间。该值以毫秒为单位。
	 */
	@Value("${socketio.pintInterval}")
	private int pingInterval;

	@Bean
	public SocketIOServer socketIOServer() {
		SocketConfig socketConfig = new SocketConfig();
		socketConfig.setTcpNoDelay(true);
		socketConfig.setSoLinger(0);
		com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
		buildSocketConfig(socketConfig,config);
		return new SocketIOServer(config);
	}

	/**
	 * 扫描netty-socketIo的注解( @OnConnect、@OnEvent等）
	 */
	@Bean
	public SpringAnnotationScanner springAnnotationScanner(){
		return new SpringAnnotationScanner(socketIOServer());
	}

	private void buildSocketConfig(SocketConfig socketConfig, com.corundumstudio.socketio.Configuration config) {
		config.setSocketConfig(socketConfig);
		config.setHostname(host);
		config.setPort(port);
		config.setBossThreads(bossCount);
		config.setWorkerThreads(workCount);
		config.setAllowCustomRequests(allowCustomRequests);
		config.setUpgradeTimeout(upgradeTimeout);
		config.setPingTimeout(pingTimeout);
		config.setPingInterval(pingInterval);
	}
}
